from flask_restful import Resource, reqparse
from flask import request
from models import db, Family, FamilyMember
from utils import api_response

class FamilyList(Resource):
    def get(self):
        """获取家庭列表"""
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, default=1, location='args')
        parser.add_argument('size', type=int, default=10, location='args')
        args = parser.parse_args()
        
        families = Family.query.paginate(
            page=args['page'], 
            per_page=args['size'], 
            error_out=False
        )
        
        return api_response({
            'total': families.total,
            'page': args['page'],
            'size': args['size'],
            'families': [family.to_dict() for family in families.items]
        })
    
    def post(self):
        """创建家庭"""
        parser = reqparse.RequestParser()
        parser.add_argument('family_name', type=str, required=True, help='家庭名称不能为空')
        parser.add_argument('creator_id', type=int, required=True, help='创建者ID不能为空')
        args = parser.parse_args()
        
        family = Family(
            family_name=args['family_name'],
            creator_id=args['creator_id']
        )
        
        db.session.add(family)
        db.session.flush()  # 获取family.id
        
        # 创建家庭成员关系（创建者）
        member = FamilyMember(
            family_id=family.id,
            user_id=args['creator_id'],
            role='creator'
        )
        
        db.session.add(member)
        db.session.commit()
        
        return api_response(family.to_dict(), message='家庭创建成功')

class FamilyDetail(Resource):
    def get(self, family_id):
        """获取家庭详情"""
        family = Family.query.get(family_id)
        if not family:
            return api_response({'message': '家庭不存在'}, code=404)
        
        # 获取家庭成员
        members = FamilyMember.query.filter_by(family_id=family_id).all()
        
        result = family.to_dict()
        result['members'] = [member.to_dict() for member in members]
        
        return api_response(result)
    
    def put(self, family_id):
        """更新家庭信息"""
        family = Family.query.get(family_id)
        if not family:
            return api_response({'message': '家庭不存在'}, code=404)
        
        parser = reqparse.RequestParser()
        parser.add_argument('family_name', type=str)
        args = parser.parse_args()
        
        if args['family_name'] is not None:
            family.family_name = args['family_name']
        
        db.session.commit()
        
        return api_response(family.to_dict(), message='家庭信息更新成功')
    
    def delete(self, family_id):
        """删除家庭"""
        family = Family.query.get(family_id)
        if not family:
            return api_response({'message': '家庭不存在'}, code=404)
        
        db.session.delete(family)
        db.session.commit()
        
        return api_response(None, message='家庭删除成功')